<?php 
class UploadImage extends UploadHandler
{
	function __construct($options=null) {
		parent::__construct($options);
		$this->model = import('model.image',true);
	}
	protected function create_file_name($uploaded_file, &$file){
		$file->origin_name = $file->name;
		if(!Core::mustLogin()){
		    $file->error = 'Must login';
		    return;
		}
		list($img_width, $img_height) = getimagesize($uploaded_file);
		$id = $this->model->save(array(
			ModelImage::F_USER_ID  	=> Core::user(),
			ModelImage::F_MODEL_ID  => 0,
			ModelImage::F_MODEL  	=> 'tmp',
			ModelImage::F_FILE  	=> $file->name,
			ModelImage::F_FILENAME  => 'tmp',
			ModelImage::F_CREATED  	=> Core::date(),
			ModelImage::F_SIZE  	=> $file->size,
			ModelImage::F_MIME_TYPE => $file->type,
			ModelImage::F_WIDTH  	=> $img_width,
			ModelImage::F_HEIGHT  	=> $img_height,
			ModelImage::F_SORT  	=> 0
		));
		if(is_numeric($id)){
			$ext = explode('/', $file->type);
            $file->name = $id.'.'.$ext[1];
            $file->id = $id;
            $this->model->save(array(ModelImage::F_FILENAME => $file->name),$file->id);
        }else{
        	$file->error = $id;
        }
    }
    protected function getFileNameById($id, $real=false){
        if(!is_numeric($id)) return $id;
        $ext = $this->model->loadOne($id,array($real ? ModelImage::F_FILE : ModelImage::F_MIME_TYPE));
        if(is_array($ext)) return $id;
        $ext = explode('/', $ext);
        return $id.'.'.$ext[1];
    }

    public function preDelete(){
    	$filename = isset($_REQUEST['file']) ? (int) $this->getFileNameById(basename(stripslashes($_REQUEST['file']))) : 0;
    	if($filename){
    		$info = $this->model->loadOne($filename, array(ModelImage::F_MODEL, ModelImage::F_MODEL_ID));
    		if($info){
    			if($info[ModelImage::F_MODEL] != 'tmp')import('model.' . $info[ModelImage::F_MODEL] ,true)->save(array(ModelImage::F_IMAGE_ID => 0), $info[ModelImage::F_MODEL_ID]);
    			$this->delete();
    			$this->model->delete($filename);
    			return;
    		}
    	}
    	echo 'true';
    }
}